package com.qf.FinancialManagement.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.common.utils.Result;
import com.qf.FinancialManagement.domain.Settlement;
import com.qf.FinancialManagement.domain.SettlementImportDTO;
import com.qf.FinancialManagement.mapper.SettlementMapper;
import com.qf.FinancialManagement.service.SettlementService;
import com.qf.common.utils.bean.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * ---好运常在---
 *
 * @author ChengShuaiKe
 * @date 2025/9/6 0006
 * @desc
 */
@Service
public class SettlementServiceImpl extends ServiceImpl<SettlementMapper, Settlement> implements SettlementService {
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result batchImport(List<SettlementImportDTO> importList) {
        if (importList == null || importList.isEmpty()) {
            return Result.error("导入数据不能为空");
        }

        // 1. 数据验证和转换
        List<Settlement> settlementList = new ArrayList<>();
        List<String> errorMessages = new ArrayList<>();

        for (int i = 0; i < importList.size(); i++) {
            SettlementImportDTO dto = importList.get(i);
            int rowNum = i + 2; // Excel行号从2开始(标题行+数据行)

            try {
                // 验证对账单号唯一性
                QueryWrapper<Settlement> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("statement_no", dto.getStatementNo());
                if (baseMapper.selectCount(queryWrapper) > 0) {
                    errorMessages.add(String.format("第%d行：对账单号【%s】已存在", rowNum, dto.getStatementNo()));
                    continue;
                }

                // DTO转实体
                Settlement settlement = new Settlement();
                BeanUtils.copyProperties(dto, settlement);

                // 设置默认值和系统字段
                settlement.setCreateTime(new Date());
                settlement.setUpdateTime(new Date());
                if (dto.getCreator() == null || dto.getCreator().trim().isEmpty()) {
                    settlement.setCreator("system"); // 默认创建人
                }

                settlementList.add(settlement);
            } catch (Exception e) {
                errorMessages.add(String.format("第%d行：数据转换失败 - %s", rowNum, e.getMessage()));
            }
        }

        // 2. 处理错误信息
        if (!errorMessages.isEmpty()) {
            return Result.error("导入失败", errorMessages);
        }

        // 3. 批量保存数据
        boolean success = this.saveBatch(settlementList);
        if (success) {
            return Result.success("导入成功", String.format("共导入 %d 条数据", settlementList.size()));
        } else {
            return Result.error("导入失败，请重试");
        }
    }
}
